﻿using MediatR;
using W.Purchase.API.Application.Command.ProcurementCommand;
using W.Purchase.Repository.Interface;

namespace W.Purchase.API.Application.CommandHandler.ProcurementCommandHandler
{
    public class ProcurementRecordedCommandHandler : IRequestHandler<ProcurementRecordedCommand, ApiResult<int>>
    {
        private readonly ILogger<ProcurementRecordedCommandHandler> _logger;
        private readonly IProcurementRepository _procurementRepository;
        private readonly IBuyProductsRepository _buyProductsRepository;
        public ProcurementRecordedCommandHandler(ILogger<ProcurementRecordedCommandHandler> logger, IProcurementRepository procurementRepository, IBuyProductsRepository buyProductsRepository)
        {
            _logger = logger;
            _procurementRepository = procurementRepository;
            _buyProductsRepository = buyProductsRepository;
        }
        public async Task<ApiResult<int>> Handle(ProcurementRecordedCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                var plist = await _procurementRepository.GetAllAsaync();
                var blist = await _buyProductsRepository.GetAllAsaync();
                var list = (from a in plist
                            join b in blist
                            on a.ProcurementId equals b.ProcurementId
                            where b.BuyProductsId == request.buyProductsId && a.IsDelete == false && b.IsDelete == false
                            select b).FirstOrDefault();
                if (list != null)
                {
                    list.IsRecorded = true;
                }
                _logger.LogInformation("采购入账成功");
                result.Code = await _buyProductsRepository.Update(list);
            }
            catch (Exception el)
            {
                result.Code = -1;
                result.Message = el.Message;
                _logger.LogError(el, el.Message);
                //throw;
            }
            return result;
        }
    }
}
